<?php
/**
 *      [迷你云] (C)2009-2012 南京恒为网络科技.
 *   软件仅供研究与学习使用，如需商用，请访问www.miniyun.cn获得授权
 * 
 */
?>
<?php

class Thumbnail extends CApiComponent {
    const MAX_IMAGE_SIZE = 20971520;     
    public static $_support_types = array(
         "gif" => "image/gif",
         "jpeg" => "image/jpeg",
         "jpg" => "image/jpeg",
         "jpe" => "image/jpeg",
         "png" => "image/png",
         "tiff" => "image/tiff",
         "tif" => "image/tif",
    );
    public $fileId;         public $filePath;        public $width   = 200;          public $height  = 200;          public $quality = 75;        public $rotate  = 0;         public $sharpen = 20;        public $default = "/statics/web/images/main/thumb_large/image.gif";
    public $format  = 'PNG';     public $image;          public $isDirect = TRUE;      
    public function invoke($isPath = true) {
        set_error_handler(array ($this, 'handleError' ));
        if ($isPath) {
            $this->filePath = "/{$this->_userId}/{$this->filePath}";
            $this->filePath = CUtils::convertStandardPath($this->filePath);
            $file = UserFile::model()->findByAttributes(array("file_path" => $this->filePath,
                                                              "user_id" => $this->_userId));
        } else {
            $file = UserFile::model()->findByAttributes(array("id" => $this->fileId,
                                                              "user_id" => $this->_userId));
        }
        
        if (!$file) {
            throw new ApiException("File is NOT FOUND.");
        }
        
        $fname = $file["file_name"];
        $pathInfo = CUtils::pathinfo_utf($fname);
        $extension = $pathInfo["extension"];
        
                $this->checkExistThumbnail($fname, $file["file_size"]);
        
        $version = FileVersion::model()->findByPk($file["version_id"]);
        $signature = $version["file_signature"];
        
                                $thumbnail  = THUMBNAIL_TEMP . CUtils::getPathBySplitStr($signature);
        $thumbnail .= "_{$this->width}_{$this->height}.{$this->format}";
                if (file_exists($thumbnail) == true) {
            $this->image  = Yii::app()->image->load($thumbnail);
            $this->handleEnd();
        }
        
        $storePath = DOCUMENT_ROOT_BLOCK . CUtils::getPathBySplitStr($signature);
        if (file_exists($storePath) == false) {
            throw new ApiException("File is NOT FOUND.");
        }
        $tmpPath = DOCUMENT_TEMP . $signature . ".{$extension}";
        $this->handleConvert($storePath,$tmpPath,$thumbnail);
        $this->handleEnd();
                unlink($tmpPath);
    }
    
    
    
    public function checkExistThumbnail($file_name, $size) {
        if ($size == 0 || $size > self::MAX_IMAGE_SIZE) {
            throw new ApiException("File don't have thumbnail.");
        }
        $pathinfo  = CUtils::pathinfo_utf($file_name);
        $extension = $pathinfo["extension"];
                                if (empty(self::$_support_types[strtolower($extension)])) {
            throw new ApiException("File don't have thumbnail .");
        }
    }
    
    public function handleConvert($fromPath,$tmpPath,$thumbnail) {
                if (file_exists(dirname($tmpPath)) == false) {
            if (CUtils::MkDirs(dirname($tmpPath)) == false) {
                throw new ApiException("Make dirs failure.");
            }
        }
                if (file_exists($tmpPath) == false) {
            if (copy($fromPath, $tmpPath) == false) {
                throw new ApiException("Copy file failure.");
            }
        }
        
                if (file_exists(dirname($thumbnail)) == false) {
            if (CUtils::MkDirs(dirname($thumbnail))== false) {
                throw new ApiException("Make dirs failure.");
            }
        }
        try {
                        $this->image  = Yii::app()->image->load($tmpPath);
            $imageObject = $this->image->getImage();
            if ($imageObject["width"] > $this->width || $imageObject["height"] > $this->height) {
                $this->image->resize($this->width, $this->height)->rotate($this->rotate)->quality($this->quality)->sharpen($this->sharpen);
            }
            $this->image->save($thumbnail,0644,true);
            $this->isDirect = FALSE;
        } catch (CException $e) {
            $this->image = NULL;
            throw new ApiException($e->getMessage());
        }
    }
    
    public function handleRender() {
        if (!$this->image) {
            $errorPath = dirname(__FILE__) . "/../../.." . $this->default;
            $this->image = Yii::app()->image->load($errorPath);
        }
        $this->image->render_direct($this->isDirect);
    }
    
    public function handleEnd() {
        $this->handleRender();
        Yii::app()->end();
    }
    public function handleError($code, $message, $file, $line){
        $this->image = NULL;
        $this->handleEnd();
    }
    
    public function handleException($exception) {
        $this->handleEnd();
    }
    
    
    public function handleCache() {
                if (!isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) || !isset($_SERVER['HTTP_IF_NONE_MATCH'])) {
            return ;
        }
                $d = date_parse_from_format("D, d M Y H:i:s",$_SERVER['HTTP_IF_MODIFIED_SINCE']);
        $e = mktime($d['hour'],$d['minute'],$d['second'],$d['month'],$d['day'],$d['year']);
        if ($e - time() < 0) {
            return ;
        }
        
                if ($_SERVER['HTTP_IF_NONE_MATCH'] == md5($_SERVER['REQUEST_URI'])) {
            header('HTTP/1.1 304 Not Modified');
            header("Etag: " . $_SERVER['HTTP_IF_NONE_MATCH']);
            $offset = 60*60*24*30;             $ExpStr = "Expires: ".gmdate("D, d M Y H:i:s", time() + $offset)." GMT";
            header($ExpStr);
            header('Cache-Control: public' );
            header('Pragma: cache');
            Yii::app()->end();
        }
    }
}